﻿using BarcodeDelay.bean;
using BarcodeDelay.FrameDecoder;
using JTParcrelHelper.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class ZCMessageHelperInfo
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListDepBarcodes = new ArrayList();
        Hashtable htCurMinutes = new Hashtable();
        public event Action AddMessage;
        public event Action GotDelayBarcode;
        public event Action GotFailedBarcode;

        public bool isLastLeaveIsBig = false;

        public bool exportExcel = false;

        public int totalExcuteThreadTimes = 0;
        public int curRow = 0;
        public DateTime lastQuery = System.DateTime.Now.AddDays(1);
        AutoResetEvent myEvent = new AutoResetEvent(false);
        public event Action QueryMessageRes;
        public event Action DoneHttpResponse;
        private static ZCMessageHelperInfo instance;
        public static ZCMessageHelperInfo Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ZCMessageHelperInfo();
                }
                return instance;
            }
        }
        private bool isManual = false;
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes, string anayType)
        {
            try
            {
                totalExcuteThreadTimes = 0;
                initLog();
                m_arListDepBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }

                JTDelayHelperNew.Instance.m_arlist_Delayed_BarCodes.Clear();
                JTDelayHelperNew.Instance.m_ht_departure_BarCodes.Clear();
                m_arListDepBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseCuijianBarcodes));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;


            }
            catch (Exception ex)
            {

            }
        }



        public void parseLeaveMsgBoard(object arListDepBarcodes)
        {
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                ArrayList arListTmpC = (ArrayList)arListDepBarcodes;
                logHelp.LogHelper.Instance.writeLog(" 开始查询。。。个数 " + arListTmpC.Count.ToString());
                if (arListTmpC.Count > 10)
                {
                    isLastLeaveIsBig = true;
                }
                else
                {
                    isLastLeaveIsBig = false;
                }
                lastQuery = System.DateTime.Now.AddHours(1);


                int totalQueryCount = 0;
                ArrayList arListBarcodes = new ArrayList();
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                bool isNewStart = false;
                string barcode = "";
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                DelayAnaHelperGen.Instance.m_arlist_Delayed_BarCodes.Clear();


                if (arListTmp.Count > 0)
                {
                    arListBarcodes.Add(arListTmp.Clone());
                    arListTmp.Clear();
                }
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;


                string httpRes = "";
                ArrayList arListAllGXTask = new ArrayList();
                int curCount = 0;
                ArrayList arListTmp3 = (ArrayList)arListDepBarcodes;
                StoParams.Instance.totalParcels = arListTmp3.Count;
                foreach (ArrayList arListBarcode in m_arListDepBarcodes)
                {
                    try
                    {
                        totalExcuteThreadTimes++;
                        intProcess++;
                        int curRow = 0;
                        if (totalExcuteThreadTimes > 10)
                        {
                            int a = 0;
                        }
                        ThreadPool.QueueUserWorkItem(new WaitCallback(handleDelayThread), arListBarcode);

                        //Program.m_frmain.SetTextMessage(intProcess, m_arListDepBarcodes.Count, "");
                    }
                    catch (Exception ex)
                    {

                    }

                }
                myEvent.WaitOne();
                StoParams.Instance.resMsg = "所有单号执行完成";






            }
            catch (Exception ex)
            {


            }
            int tiot = queryServerResTime;



        }

        private void handleDelayThread(object arListBarcode)
        {
            try
            {
                ArrayList arListDepResultTmp = new ArrayList();
                string httpRes = "";
                foreach (string strBarCode in (ArrayList)arListBarcode)
                {
                    lastQuery = System.DateTime.Now;
                    try
                    {

                        System.Threading.Thread.Sleep(100);
                        //StoParams.Instance.curParces++;
                        curRow++;
                        if (curRow % 500 == 0)
                        {
                            StoParams.Instance.resMsg = "暂停1秒，防止请求过高";
                            DoneHttpResponse.Invoke();
                            System.Threading.Thread.Sleep(1000);
                        }

                        ResultBean resultBean = new ResultBean();
                        StoParams.Instance.currentBarcode = strBarCode;
                        StoParams.Instance.resMsg = "";
                        string strResponse = "";
                        ArrayList arListAllGXTask = new ArrayList();

                        bool isContainLanshouSite = false;
                        string lanshouSite = "";
                        string curSiteToken = "";



                        string assignTme = "";
                        string dispatchSite = "";
                        string dispatchSiteArrival = "";
                        string terminalDepTime = "";
                        ArrayList arListDBOrJB = new ArrayList();

                        StoParams.Instance.httpResmsg = "请求成功";
                        FrameDecoderManager.Instance.lastSendRes = System.DateTime.Now;
                        string shouldAssignTime = "";

                        Hashtable htJS = new Hashtable();

                        double delayDays = 0;
                        if (assignTme != "" && shouldAssignTime != "")
                        {
                            TimeSpan ts = Convert.ToDateTime(assignTme) - Convert.ToDateTime(shouldAssignTime);
                            delayDays = Math.Ceiling((double)ts.TotalDays);

                        }


                        Hashtable htTaskSiteArrivalMap = new Hashtable();

                        Hashtable htTaskNoDbgBean = new Hashtable();
                        string msg = "";

                        ZCInfo zcInfo = getZCInfo(strBarCode, out msg);
                        if (zcInfo.barcode == "")
                        {
                            continue;
                        }
                        if (!JTDelayHelperNew.Instance.m_ht_departure_BarCodes.ContainsKey(strBarCode))
                        {
                            JTDelayHelperNew.Instance.m_ht_departure_BarCodes[strBarCode] = zcInfo;

                            JTDelayHelperNew.Instance.m_arlist_Delayed_BarCodes.Add(zcInfo);
                        }



                        StoParams.Instance.resMsg = msg;

                        DoneHttpResponse();
                        Random rd = new Random();
                        //int sleepTime = rd.Next(50, 150);
                        System.Threading.Thread.Sleep(25);
                    }
                    catch (Exception ex)
                    {

                    }


                }//foreach
                totalExcuteThreadTimes--;
                if (totalExcuteThreadTimes == 0)
                {
                    if (StoParams.Instance.httpResmsg.Contains("成功"))
                    {
                        StoParams.Instance.httpResmsg = "所有单号执行完成";
                        StoParams.Instance.resMsg = "所有单号执行完成";

                    }



                    DoneHttpResponse.Invoke();
                    myEvent.Set();
                }
            }
            catch (Exception ex)
            {
                totalExcuteThreadTimes--;
            }
        }

        public ZCInfo getZCInfo(string barcode, out string msg)
        {
            ZCInfo zcInfo = new ZCInfo();
            msg = "";
            ArrayList arListAllRoadmap = new ArrayList();

            try
            {
                StoParams.Instance.curParces++;
                string queryUrl = "https://wdgw.jtexpress.com.cn/servicequality/arbitration/queryResults?waybillNo=" + barcode;

                JObject jObj = new JObject();

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string res = HttpClient.HttpUtil.Instance.QueryCommon(queryUrl, postData, "GET", "integratedComprehensive");

                if (res.Contains("data"))
                {
                    JObject jsonObj = (JObject)JsonConvert.DeserializeObject(res);
                    string resMsg = jsonObj["msg"].ToString();
                    msg = resMsg;
                    JArray dataArr = (JArray)jsonObj["data"];
                    if (dataArr != null)
                    {
                        JObject jsonDetails = (JObject)dataArr[0];
                        zcInfo.barcode = barcode;
                        if (jsonDetails["createNetworkName"] != null)
                        {
                            zcInfo.createNetworkName = jsonDetails["createNetworkName"].ToString();
                        }

                        if (jsonDetails["createTime"] != null)
                        {
                            zcInfo.createTime = jsonDetails["createTime"].ToString();
                        }

                        if (jsonDetails["firstType"] != null)
                        {
                            zcInfo.firstType = jsonDetails["firstType"].ToString();
                        }

                        if (jsonDetails["secondType"] != null)
                        {
                            zcInfo.secondType = jsonDetails["secondType"].ToString();
                        }

                        if (jsonDetails["exceptionDesc"] != null)
                        {
                            zcInfo.exceptionDesc = jsonDetails["exceptionDesc"].ToString();
                        }

                        if (jsonDetails["responsibilityNetworkName"] != null)
                        {
                            zcInfo.responsibilityNetworkName = jsonDetails["responsibilityNetworkName"].ToString();
                        }

                        if (jsonDetails["status"] != null)
                        {
                            zcInfo.status = jsonDetails["status"].ToString();
                            zcInfo.status = getZcStatus(zcInfo.status);
                        }
                        if (jsonDetails["closingTime"] != null)
                        {
                            zcInfo.closingTime = jsonDetails["closingTime"].ToString();
                        }

                        if (jsonDetails["arbitrationAdjudicateOpinion"] != null)
                        {
                            zcInfo.arbitrationAdjudicateOpinion = jsonDetails["arbitrationAdjudicateOpinion"].ToString();
                        }

                        if (jsonDetails["appealAdjudicateOpinion"] != null)
                        {
                            zcInfo.appealAdjudicateOpinion = jsonDetails["appealAdjudicateOpinion"].ToString();
                        }



                    }


                }
                else
                {
                    if (res.Contains("未能解析此远程名称"))
                    {
                        msg = "网络域名不通";
                    }
                    else if (res.Contains("远程服务器返回错误: (405) 不允许的方法"))
                    {
                        msg = "认证过期，请重新登录JMS，设置机器人在线";
                    }
                    else
                    {
                        msg = res;
                    }
                    //
                }


            }
            catch (Exception ex)
            {
                if (ex.ToString().Contains("登录"))
                {
                    msg = "请重新登录JMS，并重新授权，设置机器人在线";

                }
            }
            return zcInfo;
        }

        public string getZcStatus(string status)
        {
            string res = "未知";
            switch (status)
            {
                case "10":
                    res = "已结案";
                    break;
                case "2":
                    res = "已撤销";
                    break;
                case "3":
                    res = "仲裁待分配";
                    break;
                case "7":
                    res = "仲裁裁定完成";
                    break;



                default:
                    res = "未知状态";
                    break;
            }
            return res;

        }
        public void parseCuijianBarcodes(object arListDepBarcodes)
        {

            parseLeaveMsgBoard(arListDepBarcodes);
        }


        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }


            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
